package com.tmptSource.service.impl;

import com.tmpt.dto.Result;
import com.tmpt.utils.DateTool;
import com.tmpt.service.impl.DataLimitService;
import com.tmpt.utils.StringUtils;
import com.tmpt.utils.WebUtils;
import com.tmptSource.bean.*;
import com.tmptSource.enums.OwTaskStatus;
import com.tmptSource.enums.OwTaskType;
import com.tmptSource.mapper.*;
import com.tmptSource.dto.A2userDto;
import com.tmptSource.dto.PageDto;
import com.tmptSource.service.intf.IA2userService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.tmptSource.utils.dozer.MyMapper;
import com.tmptSource.utils.page.MyPageUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import org.dozer.Mapper;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * Created by wxy on 2016/7/28.
 */
@Service(value="a2userService")
@Transactional(propagation = Propagation.REQUIRED)
public class A2userService implements IA2userService {

    private Logger log = Logger.getLogger(this.getClass());
    @Autowired private DataLimitService dataLimitService;
    @Autowired private Mapper mapper;
    @Autowired private MyMapper myMapper;
    @Autowired private MyPageUtils myPageUtils;
    @Autowired
    private A2userMapper a2userMapper;
    @Autowired
    private OwSigninMapper owSigninMapper;
    @Autowired
    private OwTaskMapper owTaskMapper;
    @Autowired
    private OwIllegalRegisterMapper owIllegalRegisterMapper;
    @Autowired
    private OwRegisterDataMapper owRegisterDataMapper;
    @Autowired
    private OwCommiteeRecordMapper owCommiteeRecordMapper;

    /**
     * 数据报表统计
     * @param a2userDto
     * @param pageDto
     * @param paramMap
     * @return
     */
    @Override
    public Result<A2userDto> pagination4Sum(A2userDto a2userDto,PageDto pageDto,Map<String,Object> paramMap) {
        //数据边界控制参数
        Map<String,Object> paramMap1 = dataLimitService.getLimitParam(paramMap);

        //分页查询
        Result<A2userDto> result = myPageUtils.pagination(
                a2userDto,pageDto,
                A2user.class,
                A2userDto.class,
                a2userMapper,
                paramMap1,
                false,null);
        //统计
        Map<String,Object> resultMap = result.getResultMap();
        List<A2userDto> list = (List<A2userDto>)resultMap.get("rows");
        for(A2userDto a2userDto1:list){
            String userId = a2userDto1.getId();

            //日常计划统计
            OwTask owTask = new OwTask();
            owTask.setAssistManId(userId);
            //owTask.setOwTaskStatus(Integer.parseInt(OwTaskStatus.Done.getKeyName().toString()));
            owTask.setOwTaskType(Integer.parseInt(OwTaskType.Normal.getKeyName().toString()));
            if(!StringUtils.isNull(a2userDto.getCreatedatesum_Start())) {
                owTask.setDealTime_Start(DateTool.str2Timestamp(a2userDto.getCreatedatesum_Start(), "yyyy-MM-dd HH:mm:ss"));
            }
            if(!StringUtils.isNull(a2userDto.getCreatedatesum_End())) {
                owTask.setDealTime_End(DateTool.timestampAppend235959999(DateTool.str2Timestamp(a2userDto.getCreatedatesum_End(), "yyyy-MM-dd")));
            }
            Map<String, Object> paramMapTask = new HashMap<String, Object>();
            paramMapTask.put("bean", owTask);
            int normalTaskPlanSum = owTaskMapper.selectListCount(paramMapTask);
            a2userDto1.setNormalTaskPlanSum(String.valueOf(normalTaskPlanSum));

            //专项计划统计
            OwTask owTask1 = new OwTask();
            owTask1.setAssistManId(userId);
            //owTask1.setOwTaskStatus(Integer.parseInt(OwTaskStatus.Done.getKeyName().toString()));
            owTask1.setOwTaskType(Integer.parseInt(OwTaskType.Special.getKeyName().toString()));
            if(!StringUtils.isNull(a2userDto.getCreatedatesum_Start())) {
                owTask1.setDealTime_Start(DateTool.str2Timestamp(a2userDto.getCreatedatesum_Start(), "yyyy-MM-dd HH:mm:ss"));
            }
            if(!StringUtils.isNull(a2userDto.getCreatedatesum_End())) {
                owTask1.setDealTime_End(DateTool.timestampAppend235959999(DateTool.str2Timestamp(a2userDto.getCreatedatesum_End(), "yyyy-MM-dd")));
            }
            Map<String, Object> paramMapTask1 = new HashMap<String, Object>();
            paramMapTask1.put("bean", owTask1);
            int specialTaskPlanSum = owTaskMapper.selectListCount(paramMapTask1);
            a2userDto1.setSpecialTaskPlanSum(String.valueOf(specialTaskPlanSum));

            //违规登记
            OwIllegalRegister owIllegalRegister = new OwIllegalRegister();
            owIllegalRegister.setCreatemanId(Integer.parseInt(userId));
            if(!StringUtils.isNull(a2userDto.getCreatedatesum_Start())) {
                owIllegalRegister.setCreatedate_Start(DateTool.str2Timestamp(a2userDto.getCreatedatesum_Start(), "yyyy-MM-dd HH:mm:ss"));
            }
            if(!StringUtils.isNull(a2userDto.getCreatedatesum_End())) {
                owIllegalRegister.setCreatedate_End(DateTool.timestampAppend235959999(DateTool.str2Timestamp(a2userDto.getCreatedatesum_End(), "yyyy-MM-dd")));
            }
            Map<String, Object> paramMapIllegalRegister = new HashMap<String, Object>();
            paramMapIllegalRegister.put("bean", owIllegalRegister);
            int illegalRegisterSum = owIllegalRegisterMapper.selectListCount(paramMapIllegalRegister);
            a2userDto1.setIllegalRegisterSum(String.valueOf(illegalRegisterSum));

            //数据登记
            OwRegisterData owRegisterData = new OwRegisterData();
            owRegisterData.setCreatemanId(Integer.parseInt(userId));
            if(!StringUtils.isNull(a2userDto.getCreatedatesum_Start())) {
                owRegisterData.setCreatedate_Start(DateTool.str2Timestamp(a2userDto.getCreatedatesum_Start(), "yyyy-MM-dd HH:mm:ss"));
            }
            if(!StringUtils.isNull(a2userDto.getCreatedatesum_End())) {
                owRegisterData.setCreatedate_End(DateTool.timestampAppend235959999(DateTool.str2Timestamp(a2userDto.getCreatedatesum_End(), "yyyy-MM-dd")));
            }
            Map<String, Object> paramMapRegisterData = new HashMap<String, Object>();
            paramMapRegisterData.put("bean", owRegisterData);
            int registerDataSum = owRegisterDataMapper.selectListCount(paramMapRegisterData);
            a2userDto1.setRegisterDataSum(String.valueOf(registerDataSum));

            //社区工作
            OwCommiteeRecord owCommiteeRecord = new OwCommiteeRecord();
            owCommiteeRecord.setA2userId(Integer.parseInt(userId));
            if(!StringUtils.isNull(a2userDto.getCreatedatesum_Start())) {
                owCommiteeRecord.setRecordDate_Start(DateTool.str2Timestamp(a2userDto.getCreatedatesum_Start(), "yyyy-MM-dd HH:mm:ss"));
            }
            if(!StringUtils.isNull(a2userDto.getCreatedatesum_End())) {
                owCommiteeRecord.setRecordDate_End(DateTool.timestampAppend235959999(DateTool.str2Timestamp(a2userDto.getCreatedatesum_End(), "yyyy-MM-dd")));
            }
            Map<String, Object> paramMapCommiteeRecord = new HashMap<String, Object>();
            paramMapCommiteeRecord.put("bean", owCommiteeRecord);
            int commiteeRecordSum = owCommiteeRecordMapper.selectListCount(paramMapCommiteeRecord);
            a2userDto1.setCommiteeRecordSum(String.valueOf(commiteeRecordSum));

        }

        return result;
    }



    @Override
    public Result<A2userDto> pagination(A2userDto a2userDto,PageDto pageDto) {
        //分页查询
        Result<A2userDto> result = myPageUtils.pagination(
                a2userDto,pageDto,
                A2user.class,
                A2userDto.class,
                a2userMapper,
                false,null);

        List<A2userDto> a2userDtoList = (List<A2userDto>)result.getResultMap().get("rows");
        if(a2userDtoList!=null && a2userDtoList.size()>0) {
            for (A2userDto a2userDto1 : a2userDtoList) {
                //查看用户是否已签到
                String userId = a2userDto1.getId();
                OwSignin owSignin = new OwSignin();
                owSignin.setA2userId(Long.parseLong(userId));
                owSignin.setCreatedate_Start(DateTool.str2Timestamp(DateTool.getCurrentDateStr(), "yyyy-MM-dd"));
                Map<String, Object> mapParam = new HashMap<>();
                mapParam.put("bean",owSignin);
                int count = owSigninMapper.selectListCount(mapParam);
                if(count>0) {
                    a2userDto1.setSignStatus("已签到");
                }else{
                    a2userDto1.setSignStatus("未签到");
                }
            }
            result.getResultMap().put("rows",a2userDtoList);
        }

        return result;
    }

    /**
    * 分布查询，有数据边界控制功能
    * @param a2userDto
    * @param pageDto
    * @param paramMap
    * @return
    */
    @Override
    public Result<A2userDto> pagination(A2userDto a2userDto,PageDto pageDto,Map<String,Object> paramMap) {
        //数据边界控制参数
        Map<String,Object> paramMap1 = dataLimitService.getLimitParam(paramMap);

        //分页查询
        Result<A2userDto> result = myPageUtils.pagination(
                a2userDto,pageDto,
                A2user.class,
                A2userDto.class,
                a2userMapper,
                paramMap1,
                false,null);

        return result;
    }


    @Override
    public Result<A2userDto> selectAll() {
        Result<A2userDto> result = new Result();

        //排序
        PageDto pageDto = new PageDto();
        pageDto.setSortColumn("id");
        pageDto.setSortOrder("desc");
        Map<String,Object> mapParam = new HashMap<>();
        mapParam.put("page",pageDto);

        List<A2user> list = a2userMapper.selectAll(mapParam);
        List<A2userDto> dtoList = myMapper.map(list, A2userDto.class);
        result.setResultList(dtoList);

        return result.success();
    }

    @Override
    public Result<A2userDto> selectById(long id) {
        Result<A2userDto> result = new Result();

        A2user a2user = a2userMapper.selectById(id);
        A2userDto dto = mapper.map(a2user, A2userDto.class);
        result.setResultObj(dto);

        return result.success();
    }

    @Override
    public Result queryUserStatusByIds(String userIds) {
        Result result = new Result();

        if(!StringUtils.isNull(userIds)){
             String[] split = userIds.split(",");
//            List<A2user> userList = a2userMapper.queryUsersByIds(split);
//            List<A2userDto> userListDto = new ArrayList<>();
//            for(int i=0;i<userList.size();i++){
//                A2user a2user = userList.get(i);
//                A2userDto dto = mapper.map(a2user,A2userDto.class);
//                userListDto.add(dto);
//            }
            List list = owTaskMapper.queryUserStatusByIds(split);
            List<Map<String,Object>> listMap = new ArrayList<>();
            Map<String, Object> resultMap = new HashMap<>();
//            resultMap.put("a2userDtoList",userListDto);
            resultMap.put("userStatusList",list);
            listMap.add(resultMap);
            result.setResultList(listMap);
        }


        return result.success();
    }

    /**
        返回ID值
    */
    @Override
    public Result<A2userDto> addData(A2userDto a2userDto){
        Result<A2userDto> result = new Result();

        //封闭数据
        A2user a2user = mapper.map(a2userDto, A2user.class);
        a2user.setCreatedate(DateTool.getCurTimestamp());

        if(a2user.getSex() == null){
            a2user.setSex(0);
        }

        //验证loginname是否存在
        int countByLoginname = a2userMapper.selectListCountByLoginname(a2user.getLoginname());
        if(countByLoginname>0){
            return result.fault("登录名已存在");
        }
        //调用mapper
        long i = a2userMapper.insert(a2user);
        if(i==0){
            return result.fault("插入失败");
        }

        A2userDto dto = mapper.map(a2user,A2userDto.class);
        result.setResultObj(dto);

        return result.success();
    }

    @Autowired
    private OwWftaskUserLinkMapper owWftaskUserLinkMapper;

    /**
        返回ID值
    */
    @Override
    public Result<A2userDto> editData(A2userDto a2userDto){
        Result<A2userDto> result = new Result();

        String regionIdNewStr = a2userDto.getOwrRegionId();
        long userId = Long.parseLong(a2userDto.getId());
        String modifyman = a2userDto.getModifyman();
        A2user a2userOld = a2userMapper.selectById(userId);
        String loginnameOld = a2userOld.getLoginname();
        String loginnameNew = a2userDto.getLoginname();
        if(!loginnameOld.equals(loginnameNew)){
            //验证loginname是否存在
            int countByLoginname = a2userMapper.selectListCountByLoginname(loginnameNew);
            if(countByLoginname>0){
                return result.fault("登录名已存在");
            }
        }

        //如果regionId原来为空并且现在也是空，没有变化
        if((null==a2userOld.getOwrRegionId()||"".equals(a2userOld.getOwrRegionId()))&&(null==regionIdNewStr||""==regionIdNewStr)){

            //如果regionId原来为空，现在不为空，变化了
        }else if(null==a2userOld.getOwrRegionId()&&null!=regionIdNewStr){
            deleteOwWftaskUserTask4owr(userId,modifyman);

            //无法regionId原来不为空，现在也不为空，判断是否新旧regionId是否相等，不相等，则变化
        }else if(null!=a2userOld.getOwrRegionId()&&null!=regionIdNewStr){
            long regionIdNew = Long.parseLong(regionIdNewStr);
            long regionIdOld = a2userOld.getOwrRegionId();
            if(regionIdNew != regionIdOld){
                deleteOwWftaskUserTask4owr(userId,modifyman);
            }
        }

        //封装数据
        A2user a2user = mapper.map(a2userDto, A2user.class);
        a2user.setModifydate(DateTool.getCurTimestamp());

        //调用mapper
        long i = a2userMapper.updateById(a2user);
        if(i==0){
            return result.fault("编辑数据失败");
        }


        A2userDto dto = mapper.map(a2user,A2userDto.class);
        result.setResultObj(dto);

        return result.success();
    }

    /**
     * 删除该用户所有双随机待办任务
     * @param userId
     * @param modifyman
     */
    private void deleteOwWftaskUserTask4owr(long userId,String modifyman){
        OwWftaskUserLink owWftaskUserLinkParam = new OwWftaskUserLink();
        owWftaskUserLinkParam.setA2userId(userId);
        owWftaskUserLinkParam.setIsFinished(0);
        Map<String,Object> paramMapSearch = new HashMap<>();
        paramMapSearch.put("bean",owWftaskUserLinkParam);
        List<OwWftaskUserLink> owWftaskUserLinkList = owWftaskUserLinkMapper.selectAll(paramMapSearch);

        for(OwWftaskUserLink owWftaskUserLink: owWftaskUserLinkList){

            OwTask owTask = owTaskMapper.selectById(owWftaskUserLink.getOwTaskId());
            if(owTask.getOwTaskType() ==null || owTask.getOwTaskType() != 3){
                continue;
            }

            Map map = new HashMap();
            map.put("id", owWftaskUserLink.getId());
            map.put("modifyman", modifyman);
            map.put("modifydate", DateTool.getCurTimestamp());
            owWftaskUserLinkMapper.deleteById(map);
        }
    }
    /**
     * 删除该用户所有待办任务
     * @param userId
     * @param modifyman
     */
    private void deleteOwWftaskUserTask(long userId,String modifyman){
        OwWftaskUserLink owWftaskUserLinkParam = new OwWftaskUserLink();
        owWftaskUserLinkParam.setA2userId(userId);
        owWftaskUserLinkParam.setIsFinished(0);
        Map<String,Object> paramMapSearch = new HashMap<>();
        paramMapSearch.put("bean",owWftaskUserLinkParam);
        List<OwWftaskUserLink> owWftaskUserLinkList = owWftaskUserLinkMapper.selectAll(paramMapSearch);

        for(OwWftaskUserLink owWftaskUserLink: owWftaskUserLinkList){
            Map map = new HashMap();
            map.put("id", owWftaskUserLink.getId());
            map.put("modifyman", modifyman);
            map.put("modifydate", DateTool.getCurTimestamp());
            owWftaskUserLinkMapper.deleteById(map);
        }
    }

    /**
    伪删除记录，返回ID值
    */
    @Override
    public Result deleteById(long id,String adminMan){
        Result result = new Result();
        //删除用户账号下所有的双随机任务，注释掉，可以不删除任务
        //deleteOwWftaskUserTask(id,adminMan);
        Map<String,Object> mapParameter = new HashMap();
        mapParameter.put("id",id);
        mapParameter.put("modifyman",adminMan);
        mapParameter.put("modifydate",DateTool.getCurTimestamp());

        //调用mapper
        long i = a2userMapper.deleteById(mapParameter);
        if(i==0){
            return result.fault("删除数据失败");
        }

        return result.success();
    }





}
